<?php
/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020/9/21 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */
namespace common\models;

/**
 * This is the model class for table "{{%carousel}}".
 *
 * @property string $id
 * @property string $title 标题说明
 * @property string $description 描述
 * @property string $image 图片链接
 * @property string $bar_color 顶栏颜色值
 * @property string $url 关联链接
 * @property string $open_type 打开链接方式
 * @property int $status 状态：0下架，1上架
 * @property int $position 位置：0首页顶部
 * @property string $sort_id 排序，越大越前
 * @property int $show_level 此会员等级以上才显示
 * @property string $created_at
 * @property string $updated_at
 */
class Carousel extends BaseActiveRecord
{
    const STATUS_DOWN = 0; // 状态：下架
    const STATUS_UP = 1; // 状态：上架

    const POSITION_INDEX_PAGE_TOP = 0; // 位置 首页顶部
    const POSITION_UCENTER_INDEX_PAGE = 1; // 位置 会员中心页

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%carousel}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['status', 'position', 'sort_id', 'show_level'], 'integer'],
            [['title', 'pic', 'created_at', 'updated_at'], 'required'],
            [['title'], 'string', 'max' => 64],
            [['bar_color'], 'string', 'max' => 7],
            [['description'], 'string', 'max' => 128],
            [['pic', 'url'], 'string', 'max' => 255],
            [['pic'], 'url'],
            [['open_type'], 'in', 'range' => ['navigate', 'redirect', 'switchTab', 'outsite']],
            [['created_at', 'updated_at'], 'safe'],
        ];
    }

    /**
     * 创建
     * @return bool
     */
    public function create()
    {
        $this->created_at = $this->updated_at = date('Y-m-d H:i:s');

        if ($this->validate()) {
            return $this->save(false);
        }
        return false;
    }

    /**
     * 更新
     * @return bool
     */
    public function updateRow()
    {
        $this->updated_at = date('Y-m-d H:i:s');

        if ($this->validate()) {
            return $this->save(false);
        }
        return false;
    }

    /**
     * 获取轮播图
     * @param int $position 位置
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getListData($position)
    {
        return static::find()
            ->andWhere(['position' => $position])
            ->andWhere(['status' => static::STATUS_UP])
            ->orderBy(['sort_id' => SORT_DESC])
            ->asArray()
            ->all();
    }
}
